import json

from FileHandlers.JsonFile import JWriteSave, JReadSave
from data.Singleton import Singleton
from data.config.DefaultConfig import default_maps


class MapSaveManager(metaclass=Singleton):
    def __init__(self, saveName):
        self.saveName = saveName

        self.map_data = {}
        self.all_point = []
        self.all_dy = []

    def getPointByDy(self, DyName):
        _dict: dict = self.map_data.get(DyName)
        return list(_dict.keys())

    def getPointDetail(self, pointName, DyName=None) -> dict:
        if DyName is not None:
            point = self.map_data.get(DyName)
            if point is not None:
                interfaces = ""
                dyhaspoint = point.get(pointName) is not None
                if dyhaspoint:
                    for i in point.get(pointName).keys() :
                        if i != "config":
                            interfaces += i + " "
                    config = point.get(pointName).get("config")
                    if config is not None:
                        retr = config
                    else:
                        retr = {}
                    return {
                        "当前可交互点有": interfaces if len(interfaces) > 0 else "没有一个呢!",
                        **retr
                    }
                else:
                    return {}
        else:
            for dyName in self.map_data.keys():
                value = self.getPointDetail(pointName, DyName=dyName)
                if value is not None:
                    return value

    def newDefault(self):
        """
        创建一个新的存档
        :return:
        """
        JWriteSave(self.saveName, 'map', default_maps)  # 默认地图的存储

    def loadSave(self):
        """
        加载Save的地图数据

        :return: 当前的大地图数据 顺带设置了all_point和map_data
        """
        json = JReadSave(self.saveName, "map")
        self.map_data: dict = json
        self.all_dy = list(self.map_data.keys())
        tmp = self.map_data.values()
        self.all_point = []
        for i in tmp:
            for k in i.keys():
                self.all_point.append(k)

        self.__preRender()  # 渲染
        return self.map_data

    def __preRender(self):
        """
        文本的渲染 ： $POINT_DY$
        :return:
        """
        new_dict = {}
        for dyname, dyvalue in self.map_data.items():
            dy_json_string = json.dumps(dyvalue, ensure_ascii=False)
            dy_json_string = dy_json_string.replace("$POINT_DY$", f" {dyname} ")
            value = json.loads(dy_json_string)
            new_dict[dyname] = value
        self.map_data = new_dict

    def Save(self):
        """
        地图数据的 存档
        :return:
        """
        JWriteSave(self.saveName, "map", self.map_data)
        print("[info] 地图数据已存档")
